package org.pku_uestc.hackathon;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.pku_uestc.hackathon.bean.LightChildHolder;
import org.pku_uestc.hackathon.bean.LightGroupHolder;
import org.pku_uestc.hackathon.bean.LightInfo;
import org.pku_uestc.hackathon.sensor.SmartLight;
import org.pku_uestc.hackathon.sensor.SmartLight.SmartLightHandler;
import org.pku_uestc.hackathon.utils.PrefUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

@SuppressLint("HandlerLeak")
public class LightsActivity extends Activity {

	private static final int MESSAGE_LOADING_LIGHTINFO_DONE = 1;

	private ExpandableListView mLightsListView;
	private List<LightInfo> mList;
	private ExpandLightAdapter mLightAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lights);
		mLightsListView = (ExpandableListView) findViewById(R.id.lights_elv);
		mList = new ArrayList<LightInfo>();
		mLightAdapter = new ExpandLightAdapter(this, mList);
		mLightsListView.setGroupIndicator(getResources().getDrawable(
				R.drawable.group_indicator));
		mLightsListView.setIndicatorBounds(getWindowManager()
				.getDefaultDisplay().getWidth() - 100, getWindowManager()
				.getDefaultDisplay().getWidth());
		mLightsListView.setAdapter(mLightAdapter);
		lightThread.start();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MESSAGE_LOADING_LIGHTINFO_DONE) {
				mLightAdapter.setData(mList);
				mLightAdapter.notifyDataSetChanged();
			}
		}
	};

	Thread lightThread = new Thread() {
		@Override
		public void run() {
			mList = getLightList();
			mHandler.sendEmptyMessage(MESSAGE_LOADING_LIGHTINFO_DONE);
		}
	};

	@SuppressLint("UseSparseArrays")
	class ExpandLightAdapter extends BaseExpandableListAdapter {

		private LayoutInflater groupInflater, childInflater;

		private List<LightInfo> mLightList;

		private Map<Integer, Boolean> mIsLightsOn;

		public ExpandLightAdapter(Context context, List<LightInfo> list) {
			this.childInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.groupInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.mLightList = list;
			mIsLightsOn = new HashMap<Integer, Boolean>();
		}

		public void setData(List<LightInfo> list) {
			this.mLightList = list;
			int size = list.size();
			for (int i = 0; i < size; i++) {
				mIsLightsOn.put(i, list.get(i).isOn());
			}
		}

		public List<LightInfo> getListData() {
			return mLightList;
		}

		public Map<Integer, Boolean> getMapData() {
			return mIsLightsOn;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return mLightList.get(groupPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(final int groupPosition, int childPosition,
				boolean isLastChild, View convertView, final ViewGroup parent) {
			LightChildHolder childHolder = null;
			// LightInfo info = mLightList.get(groupPosition);
			if (convertView == null) {
				convertView = childInflater.inflate(R.layout.light_child_item,
						null);
				childHolder = new LightChildHolder();
				childHolder.brightnessSeek = (SeekBar) convertView
						.findViewById(R.id.brigthness_seekbar);
				childHolder.hueSeek = (SeekBar) convertView
						.findViewById(R.id.hue_seekbar);
				convertView.setTag(childHolder);
			} else {
				childHolder = (LightChildHolder) convertView.getTag();
			}
			childHolder.brightnessSeek.setProgress(100 - Integer
					.parseInt((PrefUtils.getStringValue(
							getApplicationContext(), "58_bri", "50"))));
			childHolder.hueSeek.setProgress(100 - Integer.parseInt((PrefUtils
					.getStringValue(getApplicationContext(), "58_hue", "50"))));
			OnSeekBarChangeListener brightnessListener = new OnSeekBarChangeListener() {

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					final Float brightness = 1 - ((float) (seekBar
							.getProgress()) / 100);
					// Toast.makeText(getApplicationContext(), brightness + "",
					// Toast.LENGTH_SHORT).show();
					SmartLight.getInstantces(58).changeState(null, true, brightness + "", null,
							new SmartLightHandler() {

								@Override
								protected void successRefresh() {
									PrefUtils.putStringValue(
											getApplicationContext(), "58_bri",
											(int) (brightness * 100) + "");
								}

								@Override
								protected void errorRefresh() {
								}
							});
				}

			};
			OnSeekBarChangeListener hueListener = new OnSeekBarChangeListener() {

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					final Float hue = 1 - ((float) (seekBar.getProgress()) / 100);
					// Toast.makeText(getApplicationContext(), hue + "",
					// Toast.LENGTH_SHORT).show();
					SmartLight.getInstantces(58).changeState(null, true, null, hue + "",
							new SmartLightHandler() {

								@Override
								protected void successRefresh() {
									PrefUtils.putStringValue(
											getApplicationContext(), "58_hue",
											(int) (hue * 100) + "");
									//((LightGroupHolder)parent.getTag()).icon.setChecked(true);
								}

								@Override
								protected void errorRefresh() {
								}
							});
				}

			};
			// 为拖动条绑定监听器
			childHolder.brightnessSeek
					.setOnSeekBarChangeListener(brightnessListener);
			childHolder.hueSeek.setOnSeekBarChangeListener(hueListener);
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return mLightList.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return mLightList.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			LightGroupHolder groupHolder = null;
			LightInfo info = mLightList.get(groupPosition);
			if (convertView == null) {
				convertView = groupInflater.inflate(R.layout.light_group_item,
						null);
				groupHolder = new LightGroupHolder();
				groupHolder.icon = (ToggleButton) convertView
						.findViewById(R.id.light_item_icon);
				groupHolder.address = (TextView) convertView
						.findViewById(R.id.light_item_address);
				groupHolder.icon
						.setOnCheckedChangeListener(new MyOnCheckedChangeListener(
								groupPosition));
				convertView.setTag(groupHolder);
			} else {
				groupHolder = (LightGroupHolder) convertView.getTag();
				groupHolder.icon
						.setOnCheckedChangeListener(new MyOnCheckedChangeListener(
								groupPosition));
			}
			groupHolder.icon.setChecked(info.isOn());
			groupHolder.address.setText(info.getAddress());
			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

	}

	class MyOnCheckedChangeListener implements OnCheckedChangeListener {

		private int position;

		public MyOnCheckedChangeListener(int position) {
			this.position = position;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			mLightAdapter.getListData().get(position).setOn(isChecked);
			mLightAdapter.getMapData().put(position, isChecked);
			mLightAdapter.notifyDataSetChanged();
			if(position == 0)
				SmartLight.getInstantces(58).changeState(null, isChecked, null, null, new SmartLightHandler() {

					@Override
					protected void successRefresh() {}

					@Override
					protected void errorRefresh() {}
				});
		}

	}

	protected List<LightInfo> getLightList() {
		List<LightInfo> list = new ArrayList<LightInfo>();
		LightInfo info;
		for (int i = 0; i < 5; i++) {
			info = new LightInfo();
			info.setAddress("Id" + " " + (58 + i));
			info.setOn(false);
			info.setHue(i * 11);
			info.setBrightness(100 - i * 11);
			list.add(info);
		}
		return list;
	}

}
